<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="nameType" style="width: 190px; margin-right: 2px;">
          <el-option
            v-for="item in nameTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
        <el-input v-model="nameText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item class="merge-item" :table-form-merge="2">
        <el-select v-model="conditionType" style="width: 250px; margin-right: 2px;">
          <el-option label="退款申请单号" value="refundBillCode" />
          <el-option label="交易订单号" value="outTradeNo" />
          <el-option label="第三方支付流水号" value="transactionId" />
          <el-option label="客户名称" value="csmName" />
        </el-select>
        <el-input v-model="conditionText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="申请时间" value="request" />
          <el-option label="处理时间" value="audit" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item label="状态" prop="reqStatus">
        <el-select v-model="query.reqStatus" placeholder="请选择">
          <el-option
            v-for="item in reqStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付渠道" prop="paymentChannel">
        <el-select v-model="query.paymentChannel" placeholder="请选择">
          <el-option
            v-for="item in paymentChannelMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="payType">
        <el-select v-model="query.payType" placeholder="请选择">
          <el-option
            v-for="item in payTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      highlight-current-row
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <audit ref="audit" :pay-type-map="payTypeMap" />
    <reject ref="reject" />
  </div>
</template>

<script>
  import { queryRefundBillList, queryExportCashTransactionFlowList, queryMap } from '@/api'
  import moment from 'dayjs'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mapGetters } from 'vuex'
  import getTreeData from '@/utils/jsonTree'
  import Audit from './components/Audit'
  import Reject from './components/Reject'

  const colorObj = {
    1: 'color:#ff0000;',
    2: 'color:#cc33ff;',
    3: 'color:#330066;'
  }

  export default {
    name: 'refundHandle',
    components: {
      Audit, Reject
    },
    data() {
      return {
        treeData: [],
        nameType: '',
        nameText: '',
        conditionType: 'refundBillCode',
        conditionText: '',
        dateType: 'request',
        date: [moment().startOf('day'), moment().endOf('day')],
        nameTypeMap: [],
        paymentChannelMap: [],
        reqStatusMap: [],
        payTypeMap: [],
        query: {
          reqStatus: '',
          paymentChannel: '',
          payType: ''
        },
        tableData: {
          data: [],
          column: [
            {
              prop: 'refundBillCode',
              width: 150,
              fixed: 'left',
              label: '退款申请单号'
            },
            {
              prop: 'billType',
              fixed: 'left',
              label: '单据类型',
              render: (h, { row }) => <span>{ row.billType && formatColumnMap(this.nameTypeMap, 'value', row.billType, 'desc') }</span>
            },
            {
              prop: 'billCode',
              align: 'left',
              label: '单据号'
            },
            {
              prop: 'billTotalFee',
              align: 'right',
              label: '订单金额'
            },
            {
              prop: 'cashFee',
              width: 120,
              align: 'right',
              label: '支付现金金额'
            },
            {
              prop: 'refundFee',
              width: 120,
              align: 'right',
              label: '申请退款金额'
            },
            {
              prop: 'payType',
              label: '支付方式',
              render: (h, { row }) => <span>{ row.payType && formatColumnMap(this.payTypeMap, 'value', row.payType, 'desc') }</span>
            },
            {
              prop: 'paymentChannel',
              label: '支付渠道',
              render: (h, { row }) => <span>{ row.paymentChannel && formatColumnMap(this.paymentChannelMap, 'value', row.paymentChannel, 'desc') }</span>
            },
            {
              prop: 'reqStatus',
              label: '状态',
              render: (h, { row }) => <span style={colorObj[row.reqStatus]}>{ row.reqStatus && formatColumnMap(this.reqStatusMap, 'value', row.reqStatus, 'desc') }</span>
            },
            {
              prop: 'remark',
              width: 150,
              label: '备注'
            },
            {
              prop: 'reqDt',
              label: '申请时间',
              width: 180,
              render: (h, { row }) => <span>{ row.reqDt && parseTime(row.reqDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'auditor',
              label: '处理人'
            },
            {
              prop: 'auditDt',
              label: '处理时间',
              width: 180,
              render: (h, { row }) => <span>{ row.auditDt && parseTime(row.auditDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'csmName',
              label: '客户名称'
            },
            {
              prop: 'csmPhone',
              label: '客户电话',
              width: 120
            },
            {
              prop: 'csmAddress',
              label: '客户地址',
              width: 200
            },
            {
              prop: 'transactionId',
              label: '第三方支付流水号',
              width: 200
            },
            {
              prop: 'outTradeNo',
              label: '交易订单号',
              width: 120
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 80,
              render: (h, { row }) => {
                return (
                  <div>
                    <el-link size='mini' onClick={() => this.audit(row)}>
                      审核
                    </el-link>
                    <el-link size='mini' type='danger' onClick={() => this.reject(row)}>
                      驳回
                    </el-link>
                  </div>
                )
              }
            }
          ]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await Promise.all([this.getTreeData(), this.queryOptionsMap()])
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        // .orgOption & 0x01 > 0 表示移动门市
        const data = this.orgList.filter(it => it.orgOption & 0x01 > 0).map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.dateType === 'request') {
          query.reqStart = moment(this.date[0]).format()
          query.reqEnd = moment(this.date[1]).format()
        } else {
          query.auditDt = moment(this.date[0]).format()
          query.auditDtEnd = moment(this.date[1]).format()
        }
        query[this.nameType] = this.nameText
        query[this.conditionType] = this.conditionText
        const res = await queryRefundBillList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4] = await Promise.all([queryMap({ enumName: 'RefundBillStatus' }), queryMap({ enumName: 'PaymentMethod' }), queryMap({ enumName: 'PaymentChannel' }), queryMap({ enumName: 'Payment_BillType' })])
        this.reqStatusMap = res1.data // 状态
        this.payTypeMap = res2.data // 支付方式
        this.paymentChannelMap = res3.data // 支付渠道
        this.nameTypeMap = res4.data // 单据类型
      },
      async audit(row) {
        await this.$refs.audit.open(row, this.payTypeMap)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      reject(row) {
        this.$refs.reject.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryExportCashTransactionFlowList({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      reset() {
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style lang="scss" scoped>
.svg-row {
  text-align: center;
  .svg-container {
    display: inline-block;
    width: 25px;
    cursor: pointer;
    .transfer-icon {
      width: 25px;
      height: 25px;
      vertical-align: middle;
    }
  }
}
.el-form-item .el-form-item {
  margin-bottom: 0;
}
</style>
